<?php

class WishController extends BController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			//'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
/*
        public function accessRules()
        {
                return array(
                        array('allow', // allow authenticated user to perform 'index' and 'view' actions
                                'actions'=>array('index','view','claim'),
                                'users'=>array('@'),
                        ),
                        array('allow', // allow admin user to perform 'create' 'update' 'admin' and 'delete' actions
                                'actions'=>array('create','update','removeAuthor','createAuthor','admin','delete'),
                                'users'=>array('admin'),
                        ),
                        array('deny',  // deny all users
                                'users'=>array('*'),
                        ),
                );
        }
*/

	/**
	 * Claims a specified wish.
	 * @param integer $id the ID of the wish to be claimed
	 */
	public function actionClaim($id)
	{
                // request must be made via ajax
                if(isset($_GET['ajax'])) {
                        $model=$this->loadModel($id);
			// if the wish was claimed by the user, toggle it off
			if ($model->got_it == Yii::app()->user->getId()) {
				$model-> got_it = new CDbExpression('NULL'); 
			}
			// if the wish was claimed by no one, toggle it on
			if ($model->got_it == null) {
				$model->got_it = Yii::app()->user->getId();
			}
			$model->save();
                }
                else
                        throw new CHttpException(400,'Invalid request.');
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
        public function actionCreate()
        {
                $model=new Wish;
                $this->create($model);
        }

        public function actionUpdate($id)
        {       
                $model=$this->loadModel($id);
                $this->update($model);
        }

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		if(Yii::app()->user->getName() == 'admin') {
			$dataProvider=new CActiveDataProvider('Wish');
		} else {
			$dataProvider=new CActiveDataProvider('Wish', array(
				'criteria' => array(
					'condition' => 'got_it is null OR ' . 
						'got_it=' . Yii::app()->user->getId(),
				)
			));
		}
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Wish('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Wish']))
			$model->attributes=$_GET['Wish'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Wish::model()
			->with('type')
			->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='wish-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

        protected function saveAssociation($model, $author)
        {
                // record wish/author association
                $wa = new WishAuthor;
                $wa->wish_id = $model->id;
                $wa->author_id = $author->id;
                $wa->save();    
        }
}
